﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32;
using System.Security.Cryptography;
using System.IO;
using System.Collections;
using System.Data;
using System.Reflection;
using System.Xml;
using System.Runtime.InteropServices;
using System.Threading;
using System.Text.RegularExpressions;

namespace Comm.PublicClass
{
    public class PubFunction
    {
        //
        [DllImport("User32.dll", EntryPoint = "SendMessage")]
        public static extern int SendMessage(
        int hWnd, // handle to destination window
        int Msg, // message
        string wParam, // first message parameter
        string lParam // second message parameter
        );  //用于向UI发送普通信息

        
        
        /// <summary>
        /// 得到GUID
        /// </summary>
        /// <returns></returns>
        public static string GetNewGuidStr()
        {
            try
            {
                return System.Guid.NewGuid().ToString().ToLower();
            }
            catch (Exception ex)
            {
                return null;

            }
        }
        /// <summary>
        /// 得到当前运行程序目录
        /// </summary>
        /// <returns></returns>
        public static string GetAppDirectory()
        {
            try
            {
                return System.Environment.CurrentDirectory;
            }
            catch (Exception ex)
            {
                return null;

            }
        }

        /// <summary>
        /// 根据字符串型串口号获取整型串口号
        /// </summary>
        /// <param name="commstr">COM1/COM2……</param>
        /// <returns>整型的串口号</returns>
        public static int GetCommNO(string commstr)
        {
            try
            {
                commstr = commstr.ToUpper();
                int p = commstr.IndexOf("M");
                if (p < 0)
                    return 0;
                commstr = commstr.Substring(p + 1, commstr.Length - p - 1);
                return Convert.ToInt32(commstr);
            }
            catch (Exception ex)
            {
                return -1;

            }
        }

        
        /// <summary>
        /// 获取串口列表 ，并从小到大排序
        /// </summary>
        /// <returns>字符串列表</returns>
        //public static List<string> GetSerialPort()
        //{
        //    try
        //    {
        //        List<string> RegCommInfo = new List<string>();
        //        RegistryKey keyCom = Registry.LocalMachine.OpenSubKey("Hardware\\DeviceMap\\SerialComm");
        //        if (keyCom != null)
        //        {
        //            string[] sSubKeys = keyCom.GetValueNames();
        //            foreach (string sName in sSubKeys)
        //            {
        //                string sValue = (string)keyCom.GetValue(sName);
        //                RegCommInfo.Add(sValue);
        //            }

        //            //排序
        //            string tmpcomm;
        //            for (int i = 0; i < RegCommInfo.Count; i++)
        //            {
        //                for (int j = i + 1; j < RegCommInfo.Count; j++)
        //                {
        //                    if (PubFunction.GetCommNO(RegCommInfo[j]) < PubFunction.GetCommNO(RegCommInfo[i]))
        //                    {
        //                        tmpcomm = RegCommInfo[i];
        //                        RegCommInfo[i] = RegCommInfo[j];
        //                        RegCommInfo[j] = tmpcomm;

        //                    }
        //                }

        //            }
        //        }
        //        return RegCommInfo;
        //    }
        //    catch (Exception ex)
        //    {
        //        return null;

        //    }
        //}

        private const string EncryptKey = "Wang";//定义密钥

        /// <summary>
        /// 字符串加密
        /// </summary>
        /// <param name="str">要加密的字符串</param>
        /// <returns></returns>
        public static string Encrypt(string str)
        {
            if (str == string.Empty) return str;
            try
            {
                DESCryptoServiceProvider desc = new DESCryptoServiceProvider();//实例化加密解密对象

                byte[] key = Encoding.Unicode.GetBytes(EncryptKey);//定义字节数组、用来存储密钥

                byte[] data = Encoding.Unicode.GetBytes(str);//定义字节数组、用来存储要解密的字符串
                MemoryStream mstream = new MemoryStream();//实例化内存流对象
                //使用内存流实例化加密流对象

                CryptoStream cstream = new CryptoStream(mstream, desc.CreateEncryptor(key, key), CryptoStreamMode.Write);
                cstream.Write(data, 0, data.Length);//向加密流中写入数据

                cstream.FlushFinalBlock();//释放加密流

                return Convert.ToBase64String(mstream.ToArray());//返回加密后的字符串

            }
            catch
            {
                return str;
            }
        }
        /// <summary>
        /// 字符串解密
        /// </summary>
        /// <param name="str">要解密的字符串</param>
        /// <returns></returns>
        public static string Decrypt(string str)
        {
            if (str == string.Empty) return str;
            try
            {
                DESCryptoServiceProvider desc = new DESCryptoServiceProvider();//实例化加密、解密对象

                byte[] key = Encoding.Unicode.GetBytes(EncryptKey);//定义字节数组用来存储密钥
                byte[] data = Convert.FromBase64String(str);//定义字节数组、用来存储要解密的字符串
                MemoryStream mstream = new MemoryStream();//实例化内存流对象
                //使用内存流实例化解密对象
                CryptoStream cstream = new CryptoStream(mstream, desc.CreateDecryptor(key, key), CryptoStreamMode.Write);
                cstream.Write(data, 0, data.Length);//向解密流中写入数据

                cstream.FlushFinalBlock();//释放解密流

                return Encoding.Unicode.GetString(mstream.ToArray());
            }
            catch
            {
                return str;
            }
        }

        /// <summary>
        /// 得到有用的字符串，去掉\0后的字符
        /// </summary>
        /// <param name="sStr"></param>
        /// <returns></returns>
        public static string getUsefulString(string sStr)
        {
            try
            {
                int iIndex = sStr.IndexOf((char)0);
                if (iIndex > 0)
                {
                    return sStr.Substring(0, sStr.IndexOf((char)0));
                }
                else
                {
                    return sStr;
                }
            }
            catch (Exception ex)
            {
                return null;

            }
        }

        /// <summary>
        /// 根据字符串，拆分字符串，相当于vb中的split函数
        /// </summary>
        /// <param name="source">原字符串</param>
        /// <param name="ch">分隔字符串</param>
        /// <returns></returns>
        public static string[] Split(string source, string ch)
        {
            string[] resultstr = null;

            if (source == null || ch == null || source.Length == 0 || ch.Length == 0) return null;
            try
            {
                //初始化一个数组列表(当做动态数组)  
                ArrayList tmp3 = new ArrayList();
                int p = source.IndexOf(ch);
                while (p >= 0)
                {
                    tmp3.Add(source.Substring(0, p));
                    source = source.Substring(p + ch.Length, source.Length - (p + ch.Length));
                    p = source.IndexOf(ch);
                }
                if (source != "")
                    tmp3.Add(source);
                //将动态数组的维数设置成实际存在的元素个数，因为数组列表是以16的倍数递增维数的  
                tmp3.TrimToSize();
                //转换数组列表为字符串数组，并返回。  
                resultstr = (string[])tmp3.ToArray(typeof(String));

            }
            catch (Exception e)
            {
                resultstr = null;
            }
            return resultstr;

        }


        
        /// <summary>
        /// table转json
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static string DataTableToJson(DataTable dt)
        {
            StringBuilder jsonBuilder = new StringBuilder();
            jsonBuilder.Append("{\"");
            jsonBuilder.Append(dt.TableName.ToString());
            jsonBuilder.Append("\":[");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                jsonBuilder.Append("{");
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    jsonBuilder.Append("\"");
                    jsonBuilder.Append(dt.Columns[j].ColumnName);
                    jsonBuilder.Append("\":\"");
                    jsonBuilder.Append(dt.Rows[i][j].ToString());
                    jsonBuilder.Append("\",");
                }
                jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
                jsonBuilder.Append("},");
            }
            jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
            jsonBuilder.Append("]");
            jsonBuilder.Append("}");
            return jsonBuilder.ToString();
        }

        /// <summary>
        /// json转DataTable
        /// </summary>
        /// <param name="strJson"></param>
        /// <returns></returns>
        public static DataTable JsonToDataTable(string strJson)
        {
            //取出表名  
            //Regex rg = new Regex(@"(?<={)[^:]+(?=:/})", RegexOptions.IgnoreCase);
            //string strName = rg.Match(strJson).Value;
            DataTable tb = null;
            //去除表名  
            strJson = strJson.Substring(strJson.IndexOf("[") + 1);
            strJson = strJson.Substring(0, strJson.IndexOf("]"));

            //获取数据  
            Regex rg = new Regex(@"(?<={)[^}]+(?=})");
            MatchCollection mc = rg.Matches(strJson);
            for (int i = 0; i < mc.Count; i++)
            {
                string strRow = mc[i].Value;
                string[] strRows = strRow.Split(',');

                //创建表  
                if (tb == null)
                {
                    tb = new DataTable();
                    tb.TableName = "";
                    foreach (string str in strRows)
                    {
                        DataColumn dc = new DataColumn();
                        string[] strCell = str.Split(':');
                        dc.ColumnName = strCell[0].ToString();
                        tb.Columns.Add(dc);
                    }
                    tb.AcceptChanges();
                }

                //增加内容  
                DataRow dr = tb.NewRow();
                for (int r = 0; r < strRows.Length; r++)
                {
                    dr[r] = strRows[r].Split(':')[1].Trim().Replace("，", ",").Replace("：", ":").Replace("\"", "");
                }
                tb.Rows.Add(dr);
                tb.AcceptChanges();
            }

            return tb;
        }


        /// <summary>
        /// 复制类属性 3参数
        /// </summary>
        /// <param name="fromFields"></param>
        /// <param name="fromRecord"></param>
        /// <param name="toRecord"></param>
        public static void SetProperties(PropertyInfo[] fromFields,
                                         object fromRecord,
                                         object toRecord)
        {
            PropertyInfo fromField = null;

            try
            {

                if (fromFields == null)
                {
                    return;
                }

                for (int f = 0; f < fromFields.Length; f++)
                {

                    fromField = (PropertyInfo)fromFields[f];

                    fromField.SetValue(toRecord,
                                       fromField.GetValue(fromRecord, null),
                                       null);
                }

            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 以空格拆分字符串。
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static string SplitStr(string source)
        {
            if (string.IsNullOrEmpty(source))
                return string.Empty;
            
            string stringOut = string.Empty;
            int length = source.Length / 2;

            for (int i = 0; i < length; i++)
            {
                string str = source.Substring(i * 2, 2);
                if (!IsHexStr(str))  //非十六进制数不拆分
                    return source;
                
                stringOut += str + " ";
            }

            return stringOut.Trim();//去掉最后一个空
        }

        /// <summary>
        /// 等待多少毫秒
        /// </summary>
        /// <param name="iSecond"></param>
        public static void SleepMillSecond(int iSecond)
        {
            DateTime current = DateTime.Now;
            while (current.AddMilliseconds(iSecond) > DateTime.Now)
            {
            }

        }

        /// <summary>
        /// 判断是否字符串由十六进制字符组成
        /// </summary>
        /// <param name="astr"></param>
        /// <returns></returns>
        public static bool IsHexStr(string astr)
        {
            bool rs = true;
            astr = astr.ToUpper();
            const string constr = "1234567890ABCDEF";
            for (int i = 0; i < astr.Length; i++)
            {
                rs = constr.Contains(astr[i]);
                if (!rs)
                    break;
            }
            return rs;
        }


        /// <summary>
        /// 当前日期时间转为数字
        /// </summary>
        /// <param name="atime"></param>
        /// <returns></returns>
        public static Int64 DateTimeToInt()
        {
            return DateTimeToInt(DateTime.Now);
        }

        /// <summary>
        /// 日期时间转为数字
        /// </summary>
        /// <param name="atime"></param>
        /// <returns></returns>
        public static Int64 DateTimeToInt(DateTime atime)
        { 
            string str = atime.ToString("yyyyMMddHHmmssfff");
            return Convert.ToInt64(str);
        }


        /// <summary>
        /// 日期转为数字
        /// </summary>
        /// <param name="atime"></param>
        /// <returns></returns>
        public static Int64 DateToInt(DateTime atime)
        {
            string str = atime.ToString("yyyyMMdd");
            return Convert.ToInt64(str);
        }


        /// <summary>
        /// 删除文件夹
        /// </summary>
        /// <param name="strpath"></param>
        /// <returns></returns>
        public static bool DeleteDirectory(string strpath)
        {
            string[] strtemp;
            try
            {
                //先删除目录下的文件
                strtemp = Directory.GetFiles(strpath);
                foreach (string str in strtemp)
                {
                    File.Delete(str);
                }

                //删除目录  递归
                strtemp = Directory.GetDirectories(strpath);
                foreach (string str in strtemp)
                {
                    DeleteDirectory(str);
                }

                //删除该目录
                Directory.Delete(strpath);
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}
